<template>
  <div class="task-container-box common-check-container">
    <div class="common-list-bread">
      <el-button class="common-btn-solid" size="small" @click="onClickCancel"
        >返回</el-button
      >
      <span class="title"
        >{{ actionType === "edit" ? "编辑" : "录入" }}试验任务</span
      >
    </div>
    <div class="wrapper">
      <div class="task-container  common-detail-box">
        <div class="" v-loading="loading">
          <el-form
            :model="detailInfo"
            ref="detailInfo"
            :rules="rules"
            label-width="190px"
            class="add-form"
          >
            <el-form-item label="试验名称：" prop="name" class="width-160">
              <el-input
                clearable
                :maxlength="15"
                v-model="detailInfo.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="试验代号：" prop="code" class="width-160">
              <el-input
                clearable
                :maxlength="10"
                v-model="detailInfo.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <!-- <el-form-item label="试验负责人：" prop="principal" class="width-160">
            <el-select v-model="detailInfo.principal" clearable filterable >
              <el-option v-for="item in principalList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="被测装备：" prop="equipmentUnderTestArr" class="equipment">
            <el-select v-model="detailInfo.equipmentUnderTestArr"  multiple clearable filterable >
              <el-option v-for="item in equipmentUnderTestList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item> -->
            <el-form-item label="使命主题：" class="theme">
              <el-input
                :maxlength="100"
                v-model="detailInfo.theme"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item required label="任务时间：" class="width-160">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="detailInfo.startDate"
                type="date"
                :clearable="false"
                :editable="false"
                placeholder="请选择"
              >
              </el-date-picker>
              至
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="detailInfo.endDate"
                type="date"
                :clearable="false"
                :editable="false"
                placeholder="请选择"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="试验描述：" class="describe">
              <el-input
                type="textarea"
                :maxlength="1000"
                :autosize="{ minRows: 5 }"
                v-model="detailInfo.describe"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label=" " class="upload-content">
              <el-upload
                class=""
                action="/api/majorTaskRecord/uploadFile"
                multiple
                :limit="5"
                :before-upload="beforeUpload"
                :on-progress="handleProgress"
                :on-success="handleSuccess"
                :on-error="handleError"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                accept=".docx,image/png,image/jpeg,image/jpg,image/gif,application/pdf,application/msword,application/vnd.ms-excel "
                :file-list="detailInfo.commonUrlNameList"
                v-model="detailInfo.commonUrlNameList"
                name="file"
              >
                <el-button class="common-btn-solid blue" size="small" 
                  >上传附件</el-button
                >
                <div slot="tip" class="upload-tip">
                  支持上传不大于20M的pdf、word、excel、jpg、png、gif格式的文件
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item label="场地需求：" class="describe">
              <el-checkbox-group v-model="siteCheckList">
                <el-checkbox
                  v-for="item in siteList"
                  :key="item.id"
                  :label="item.name"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="人员需求：" class="describe">
              <el-checkbox-group v-model="personnelCheckList">
                <el-checkbox
                  v-for="item in personnelList"
                  :key="item.id"
                  :label="item.name"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="装备需求：" class="describe">
              <el-checkbox-group v-model="equipmentCheckList">
                <el-checkbox
                  v-for="item in equipmentList"
                  :key="item.id"
                  :label="item.name"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="common-footer">
      <el-button class="common-btn-primary" @click="onClickSaveData"
        >保存</el-button
      >
      <el-button class="common-btn-solid" @click="onClickCancel"
        >取消</el-button
      >
    </div>
    </div>
    
  </div>
</template>
<script>
export default {
  data() {
    const validScore = (rule, value, callback) => {
      if (!this.detailInfo.adjustmentType) {
        callback(new Error("请选择增扣分"));
      } else if (!this.detailInfo.score) {
        callback(new Error("请进行増扣分填写"));
      } else {
        callback();
      }
    };
    return {
      queryParams: {}, //列表页查询参数
      loading: false,
      detailInfo: {
        name: "", //试验名称
        code: "", //试验代号
        principal: "", //试验负责人
        equipmentUnderTestArr: [], //被测装备
        theme: "", //使命主题
        startDate: "", //任务开始时间
        endDate: "", //任务结束时间
        describe: "", //试验描述
        commonUrlNameList: [], //上传
      },
      isUploading: false, //是否有正在上传的资料
      equipmentUnderTestList: [], //被测装备数据集合
      principalList: [], //负责人数据集合
      rules: {
        name: [
          {
            required: true,
            message: "请输入试验名称",
            trigger: ["blur", "change"],
          },
        ],
        code: [
          {
            required: true,
            message: "请输入试验代号",
            trigger: ["blur", "change"],
          },
        ],
        principal: [
          {
            required: true,
            message: "请输入试验负责人",
            trigger: ["blur", "change"],
          },
        ],
        adjustmentType: [
          {
            required: true,
            validator: validScore,
            trigger: ["blur", "change"],
          },
        ],
        equipmentUnderTestArr: [
          {
            required: true,
            message: "请选择被测装备",
            /* validator: validScore, */ trigger: ["blur", "change"],
          },
        ],
      },
      siteList: [], //场地集合
      personnelList: [], //人员集合
      equipmentList: [], //装备集合
      siteCheckList: [], //场地需求 选中集合
      personnelCheckList: [], //人员需求 选中集合
      equipmentCheckList: [], //装备需求 选中集合
    };
  },
  created() {
    this.queryParams = this.$route.query;
    this.actionType = this.$route.params.action;

    //获取下拉列表数据
    /* this.asyncGetPrincipalList();
      this.asyncGetEquipmentUnderTestList(); */

    if (this.actionType === "editTask") {
      this.asyncGetDetailData(this.queryParams.currentTabId);
    } else {
      /*  this.asyncGetPersonnelList();
        this.asyncGetSiteList();
        this.asyncGetEquipmentList(); */
    }
  },
  methods: {
    //上传前校验
    beforeUpload(file) {
      const fileSize = file.size / 1024 / 1024 < 20;
      if (!fileSize) {
        this.$message.warning("上传文件大小不超过20M");
        return false;
      }
    },
    //文件上传时
    handleProgress() {
      this.isUploading = true;
    },
    //文件上传成功时
    handleSuccess(res, file, fileList) {
      //错误处理
      if (res.code !== 200) {
        this.$message.error(res.msg);
      }
      let completed = false;
      if (fileList && fileList.length > 0) {
        completed = fileList.every((item) => {
          return item.status === "success";
        });
      }
      if (completed) {
        let _fileList = [];
        fileList.forEach((item) => {
          if (!item.response) {
            _fileList.push(item);
          } else if (item.response.code === 200) {
            this.$set(item.response.data, "name", item.response.data.fileName);
            this.$set(item.response.data, "url", item.response.data.fileUrl);
            _fileList.push(item.response.data);
          }
        });
        this.detailInfo.commonUrlNameList = _fileList;
        this.isUploading = false;
      }
    },
    //文件上传失败时
    handleError() {
      this.isUploading = false;
    },
    //文件列表移除文件时
    handleRemove(file, fileList) {
      let _isCompleted = null;
      if (fileList && fileList.length > 0) {
        _isCompleted = fileList.every((item) => {
          return item.status === "success";
        });
        this.isUploading = !_isCompleted;
      } else {
        this.isUploading = false;
        this.detailInfo.commonUrlNameList = [];
      }
      this.detailInfo.commonUrlNameList = fileList;
    },
    //文件超出个数限制时
    handleExceed() {
      this.$message.warning("最多可上传5个文件");
    },
    /* siteList:[],//场地集合
        personnelList:[],//人员集合
        equipmentList:[],//装备集合
        siteCheckList:[],/ */
    //被测装备数据集合
    asyncGetEquipmentUnderTestList() {
      this.$axios.get("xxx").then((res) => {
        if (res.data.code === 200) {
          this.equipmentUnderTestList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //负责人数据集合
    asyncGetPrincipalList() {
      this.$axios.get("xxx").then((res) => {
        if (res.data.code === 200) {
          this.principalList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //场地集合
    asyncGetSiteList() {
      this.$axios.get("xxx").then((res) => {
        if (res.data.code === 200) {
          this.siteList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //人员集合
    asyncGetPersonnelList() {
      this.$axios.get("xxx").then((res) => {
        if (res.data.code === 200) {
          this.personnelList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //装备集合
    asyncGetEquipmentList() {
      this.$axios.get("xxx").then((res) => {
        if (res.data.code === 200) {
          this.equipmentList = res.data.data || [];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //回显数据
    asyncGetDetailData(id) {
      this.loading = true;
      this.$axios
        .get(
          `/experimenttask/getExperimentTaskById?id=${id}&type=2`
        )
        .then((res) => {
          if (res.data.code === 200) {
            const data = res.data.data;
            Object.keys(data).forEach((item) => {
              this.detailInfo[item] = data[item];
            });
          } else {
            this.$message.error(res.data.msg);
          }
          this.loading = false;
        });
    },
    //点击取消
    onClickCancel() {
      this.$router.push({
        path: "/experimentTask",
        // query: this.queryParams
      });
    },
    //点击保存
    onClickSaveData() {
      this.$refs["detailInfo"].validate((valid) => {
        if (valid) {
          if (!this.detailInfo.startDate || !this.detailInfo.endDate) {
            this.$message.error("请完善任务时间");
            return;
          } else if (this.detailInfo.startDate > this.detailInfo.endDate) {
            this.$message.error("任务开始时间不能大于结束时间");
            return;
          }
          const url =
            this.actionType !== "edit"
              ? "/scoreAdjustmentRecord/saveScoreAdjustmentRecord"
              : "/scoreAdjustmentRecord/updateScoreAdjustmentRecord";
          const id =
            this.queryParams.id && this.actionType === "edit"
              ? this.queryParams.id
              : "";
          this.asyncSaveData(url, id);
        }
      });
    },
    //保存任务
    asyncSaveData(url, id) {
      this.$axios
        .post(url, {
          ...this.detailInfo,
          id,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.onClickCancel();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
  },
  computed: {},
  watch: {},
};
</script>
<style scoped>
.task-container-box {
  padding: 0;
  /* background-color: #fff; */
}
.task-container-box .common-detail-box {
  padding: 40px 0 0 0;
}
.task-container-box /deep/ .el-input__inner {
  height: 32px;
  line-height: 32px;
}
.task-container-box /deep/ .equipment .el-select,
.task-container-box /deep/ .theme .el-input,
.task-container-box /deep/ .describe .el-textarea {
  width: 80%;
}
.upload-content {
  width: 52%;
  margin-bottom: 5px;
}
.task-container-box /deep/ .describe {
  margin-bottom: 5px;
}
.upload-tip {
  height: 22px;
  line-height: 25px;
  font-size: 13px;
  color: #888888;
}
.task-container-box .width-160 /deep/ .el-input {
  width: 160px;
}
.add-form {
  padding-right: 120px;
}
.item-score {
  position: relative;
  display: inline-block;
  margin-left: 30px;
}
.title {
  padding-left: 10px;
}
.task-container {
  padding-top: 20px;
  background-color: #fff;
  /* overflow-y: auto; */
}
.wrapper {
  overflow-y: auto;
}
</style>
<style>
/*  .task-container-box .width-160 .el-input {
    width: 160px;
  } */
</style>
